import axios from "axios";
import { Notify } from "@/utils/notification";
import baseUrl from "./url";
import store from "@/store";
axios.defaults.timeout = 600000; // 设置超时时间

axios.defaults.withCredentials = true;
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=utf-8";

const errorCb = error => {
  const errmsg = error.response || error;
  if (
    errmsg?.request?.responseURL?.indexOf("gzbbn.cn-elite.com") > -1 ||
    errmsg?.config?.url.indexOf("gzbbn.cn-elite.com") > -1
  ) {
    //服务台token失效不报错
  } else {
    Notify.error({
      message: `Error:${errmsg?.data?.code} ${errmsg?.data?.msg}`
    });
  }

  return Promise.reject(error);
};
const successCb = response => {
  if ([response.data.code].includes(403)) {
    //处理后台权限问题
    Notify.error({ message: response.data.msg });
    // store.dispatch("logout");
  }
  if (
    ![response.status, response.data.code, response.data.status].includes(200)
  ) {
    // http code 为200 但是data.code不是200的情况
    return errorCb(response);
  }
  return Promise.resolve(response);
};

axios.interceptors.request.use(function(config) {
  config.headers["Content-Type"] = "application/json";
  return config;
}, errorCb);

axios.interceptors.response.use(
  // 封装拦截器，出错时弹出错误信息
  successCb,
  errorCb
);

/**
 *
 * @param {string} method  请求接口名，要带"/";
 * @param {*} params  请求接口参数
 * @returns
 */
export const get = (method, params) => {
  return axios
    .get(`${baseUrl}${method}`, {
      params
    })
    .then(res => {
      return Promise.resolve(res.data);
    });
};

/**
 *
 * @param {string} method  请求接口名，要带"/";
 * @param {*} params  请求接口参数
 * @returns
 */
export const post = (method, params) => {
  let data = params;
  if (!params instanceof FormData) {
    data = JSON.stringify(params);
  }
  return axios({
    method: "POST",
    url: `${baseUrl}${method}`,
    data
  }).then(res => {
    return Promise.resolve(res.data);
  });
};

/**
 *
 * @param {string} method  请求接口名，要带"/";
 * @param {*} params  请求接口参数
 * @returns
 */
export const remove = (method, params) => {
  return axios
    .delete(`${baseUrl}${method}`, {
      params
    })
    .then(res => {
      return Promise.resolve(res.data);
    });
};

export default axios;
